package study.ct.com.retrofit_rxjava;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import study.ct.com.retrofit_rxjava.activity.BroadcastActivity;
import study.ct.com.retrofit_rxjava.activity.ClickEvent;
import study.ct.com.retrofit_rxjava.activity.NoteActivity;
import study.ct.com.retrofit_rxjava.bin.EarningRankQueryResp;
import study.ct.com.retrofit_rxjava.bin.TvLoginOk;
import study.ct.com.retrofit_rxjava.net.Cases.CtLoginCase;
import study.ct.com.retrofit_rxjava.net.Cases.GetCitiesCase;
import study.ct.com.retrofit_rxjava.net.extension.BaseSubscriber;
import study.ct.com.retrofit_rxjava.net.models.City;
import study.ct.com.retrofit_rxjava.service.MyService;
import study.ct.com.retrofit_rxjava.util.ILog;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    private Retrofit retrofit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        //getCities();
       // getLogin();

    }

    public void initData(){

        //添加 log拦截
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(
                new HttpLoggingInterceptor.Logger(){

                    @Override
                    public void log(String message) {
                        Log.i(TAG, "log: Retrofit=>"+message);
                    }
                });

        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

        retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl("http://wap.crunii.com:81/")
                .client(client)
                .build();





        Map<String, String> map = new HashMap<String, String>();
        map.put("mobile", "18983001336");
        map.put("code", "001336");
        Gson gson=new Gson();

        String route = gson.toJson(map);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), route);

        final MyService service = retrofit.create(MyService.class);
        service.login(body)
                .flatMap(new Func1<TvLoginOk, Observable<EarningRankQueryResp>>() {//获取token
                    @Override
                    public Observable<EarningRankQueryResp> call(TvLoginOk tvLoginOk) {
                        Log.i(TAG, "call: loginok=="+tvLoginOk.getToken());
                        Gson gson=new Gson();
                        String route = gson.toJson(tvLoginOk);
                        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), route);
                        return service.loadMyEarningRank(body);
                    }
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .doOnNext(new Action1<EarningRankQueryResp>() {
                    @Override
                    public void call(EarningRankQueryResp earningRankQueryResp) {
                        Log.i(TAG, "call: enrningRankQueryResp="+earningRankQueryResp.getHandleNum());
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<EarningRankQueryResp>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError: e=="+e);
                    }

                    @Override
                    public void onNext(EarningRankQueryResp earningRankQueryResp) {

                    }
                });

    }

    public void initView(){

        findViewById(R.id.click_event).setOnClickListener(this);
        findViewById(R.id.main_layout).setOnClickListener(this);
        findViewById(R.id.main_receiver).setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        Log.i(TAG, "onClick: click=========="+view.getId());
        switch (view.getId()){
            case R.id.click_event:
                toActivity(ClickEvent.class);
                break;

            case R.id.main_layout:
                toActivity(NoteActivity.class);
                break;
            case R.id.main_receiver:
                toActivity(BroadcastActivity.class);
                break;

            default:
                ILog.i(TAG,"click=========default=====");
                break;
        }

    }

    public void toActivity(Class classes){
        Intent intent = new Intent(MainActivity.this, classes);
        startActivity(intent);
    }


    public void getCities() {
        new GetCitiesCase().getCities()
               // .compose(this.<List<City>>bindToLifecycle())
                .subscribe(new BaseSubscriber<List<City>>() {
                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(List<City> o) {
                        //getCitiesTv.setText("");

                        if (o != null && o.size() != 0) {

                            for (City city : o) {
                               // Log.i(TAG, "onNext: city ="+city.id.intValue() + "  " + city.name + "\n");
                            }
                        }
                    }
                });

    }

    public void getLogin(){

        Map<String, String> map = new HashMap<String, String>();
        map.put("mobile", "18983001336");
        map.put("code", "001336");
        Gson gson=new Gson();
        String route = gson.toJson(map);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), route);

        new CtLoginCase().getLogin(body)
                .subscribe(new BaseSubscriber<TvLoginOk>() {
                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(TvLoginOk tvLoginOk) {

                    }
                });

    }
}
